package com.dong8.activity;

import java.net.URLEncoder;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alipay.android.app.sdk.AliPay;
import com.alipay.android.msp.Keys;
import com.alipay.android.msp.Rsa;
import com.dong8.R;
import com.dong8.resp.MyInfoResp;
import com.dong8.resp.RespBase;
import com.dong8.resp.SpaceSection;
import com.dong8.resp.MyInfoResp.Member;
import com.dong8.resp.RespOrder.OrderForm;
import com.dong8.sys.Constants;
import com.dong8.sys.MyApp;
import com.dong8.util.MgqDataHandler;
import com.dong8.util.MgqRestClient;
import com.dong8.util.ToastUtil;
import com.dong8.util.Utils;
import com.loopj.android.http.RequestParams;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

@SuppressLint("HandlerLeak")
public class PayOrderActivity extends Activity implements OnClickListener
{
	OrderForm orderForm;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pay_order);
	
		findViewById(R.id.alipay).setOnClickListener(this);
		findViewById(R.id.linkpay).setOnClickListener(this);
		
		findViewById(R.id.ibBack).setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				finish();
			}
		});
		((TextView)findViewById(R.id.tv_title)).setText("支付订单");
		
		String sform = getIntent().getStringExtra("orderForm");
		orderForm = JSON.parseObject(sform, OrderForm.class);
	}

	@Override
	public void onClick(View arg0) 
	{
		switch(arg0.getId())
		{
		case R.id.alipay:
			payOrder();
			break;

		case R.id.linkpay:
			showDialog();
			break;
		}
	}
	
	public void showDialog() 
	{
		final Dialog dialog = new Dialog(this,R.style.dialog);
		dialog.setContentView(R.layout.dialog); 
		dialog.setCancelable(true);
		
		((Button)dialog.findViewById(R.id.confirm)).setText("继续");
		dialog.findViewById(R.id.confirm).setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				getMemberCard();
				dialog.dismiss();
			}
		});
		dialog.findViewById(R.id.cancel).setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				dialog.dismiss();
			}
		});

		((TextView)dialog.findViewById(R.id.msg)).setText("确认使用会员卡支付预定场地?");
		dialog.show();
	}
	
	Handler mHandler = new Handler() 
	{
		public void handleMessage(android.os.Message msg) 
		{
			if(((String) msg.obj).contains(orderForm.order_code))
			{
				getData();
			}
		};
	};
	
	@SuppressWarnings("deprecation")
	void payOrder()
	{
		try 
		{
			String info = getNewOrderInfo();
			String sign = Rsa.sign(info, Keys.PRIVATE);
			sign = URLEncoder.encode(sign);
			info += "&sign=\"" + sign + "\"&" + getSignType();

			final String orderInfo = info;
			new Thread() 
			{
				public void run() 
				{
					AliPay alipay = new AliPay(PayOrderActivity.this, mHandler);
					String result = alipay.pay(orderInfo);
					Message msg = new Message();
					msg.what = 0;
					msg.obj = result;
					mHandler.sendMessage(msg);
				}
			}.start();
		}
		catch (Exception ex)
		{
			ToastUtil.showToastWithAlertPic("签名错误");
		}
	}
	
	private String getSignType() 
	{
		return "sign_type=\"RSA\"";
	}
	
	@SuppressWarnings("deprecation")
	private String getNewOrderInfo() 
	{
		StringBuilder sb = new StringBuilder();
		sb.append("partner=\"");
		sb.append(Keys.DEFAULT_PARTNER);
		sb.append("\"&out_trade_no=\"");
		sb.append(orderForm.order_code);
		sb.append("\"&subject=\"");
		sb.append(orderForm.cust_name + "预定" + SpaceSection.getSpaceInfo(orderForm.order_item));
		sb.append("\"&body=\"");
		sb.append(orderForm.order_desc);
		sb.append("\"&total_fee=\"");
		sb.append("0.01" /*orderForm.amount*/);
		sb.append("\"&notify_url=\"");

		// 网址需要做URL编码
		sb.append(URLEncoder.encode("http://notify.java.jpxx.org/index.jsp"));
		sb.append("\"&service=\"mobile.securitypay.pay");
		sb.append("\"&_input_charset=\"UTF-8");
		sb.append("\"&return_url=\"");
		sb.append(URLEncoder.encode("http://m.alipay.com"));
		sb.append("\"&payment_type=\"1");
		sb.append("\"&seller_id=\"");
		sb.append(Keys.DEFAULT_SELLER);

		// 如果show_url值为空，可不传
		// sb.append("\"&show_url=\"");
		sb.append("\"&it_b_pay=\"1m");
		sb.append("\"");

		return new String(sb);
	}
	
	private void getData()
	{
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false)
		{
			@Override
			public void onSuccess(String response)
			{
				super.onSuccess(response);
				RespBase respUser = JSON.parseObject(response, RespBase.class);
				if (respUser.code==0) 
				{
					ToastUtil.showToastWithAlertPic("场地预定支付成功");
					if(((MyApp)getApplicationContext()).mFinishActivity != null)
					{
						String name = ((MyApp)getApplicationContext()).mFinishActivity.getClass().getName();
						if(name.contains("OrderFieldActivity"))
						{
							startActivity(new Intent(PayOrderActivity.this,MyReserveActivity.class));
						}
						
						((MyApp)getApplicationContext()).mFinishActivity.finish();
						((MyApp)getApplicationContext()).mFinishActivity = null;
					}
					MyReserveActivity.mPayResult = true;
					finish();
				}
				else 
				{
				}
			}

			public void onFailure(Throwable ble) 
			{
			}
		};

		RequestParams params = new RequestParams();
		params.put("data", orderForm.order_code);
		MgqRestClient.get(Constants.CONFIRM_ORDER, params, loginHandler);
	}
	
	private void memberPay(String card)
	{
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false)
		{
			@Override
			public void onSuccess(String response) 
			{
				super.onSuccess(response);
				RespBase respUser = JSON.parseObject(response, RespBase.class);
				if (respUser.code==0) 
				{
					getData();
				}
				else
				{
					
				}
			}

			public void onFailure(Throwable ble) 
			{
				
			}
		};

		RequestParams params = new RequestParams();
		params.put("card", card);
		params.put("price", orderForm.amount);
		params.put("sn", orderForm.order_code);
		MgqRestClient.get(((MyApp)getApplicationContext()).mCurrentGym.service + Constants.CLUB_MEMBER_PAY, params, loginHandler);
	}
	
	private void getMemberCard()
	{
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) 
		{
			@Override
			public void onSuccess(String response) 
			{
				super.onSuccess(response);
				MyInfoResp myInfoResp = JSON.parseObject(response, MyInfoResp.class);
				if (myInfoResp.code == 0) 
				{
					boolean result = false;
					int clubid = ((MyApp)getApplicationContext()).mCurrentGym.id;

					List<Member> mList = myInfoResp.member;
					int count = mList.size();
					int i = 0;
					for(; i < count; i++)
					{
						if(clubid == mList.get(i).club_id)
						{
							result = true;
							break;
						}
					}
					
					if(!result)
					{
						final Dialog dialog = new Dialog(PayOrderActivity.this,R.style.dialog);
						dialog.setContentView(R.layout.dialog); 
						dialog.setCancelable(true);
						
						((Button)dialog.findViewById(R.id.confirm)).setText("继续");
						dialog.findViewById(R.id.confirm).setOnClickListener(new OnClickListener()
						{
							@Override
							public void onClick(View arg0)
							{
								dialog.dismiss();
								startActivity(new Intent(PayOrderActivity.this,BandMemberCardActivity.class));
							}
						});
						dialog.findViewById(R.id.cancel).setOnClickListener(new OnClickListener()
						{
							@Override
							public void onClick(View arg0)
							{
								dialog.dismiss();
							}
						});
						((TextView)dialog.findViewById(R.id.msg)).setText("你还没有绑定" 
								+ ((MyApp)getApplicationContext()).mCurrentGym.clubName 
								+ "的会员卡，不能通过会员卡支付，是否绑定该场馆的会员卡?");
						dialog.show();
					}
					else
					{
						String memberCard = mList.get(i).member_card;
						memberPay(memberCard);
					}
				} 
				else
				{
					ToastUtil.showToastWithAlertPic(myInfoResp.mesg);
				}
			}

			public void onFailure(Throwable ble) 
			{
				ToastUtil.showToastWithAlertPic("数据获取失败,请重试!");
			}
		};

		RequestParams params = new RequestParams();
		params.put("id", Utils.getUserInfo(this).id);
		MgqRestClient.get(Constants.USER_MEMBER, params, loginHandler);
	}
}
